package com.smarthome.web.property.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smarthome.common.tools.SHACipher;
import com.smarthome.core.user.PropertyUserService;
import com.smarthome.core.user.UserResourceService;
import com.smarthome.domain.bean.ShUser;
import com.smarthome.domain.common.Result;
import com.smarthome.web.property.auth.ShiroRealm;
import com.smarthome.web.property.utils.UserHolder;

@Controller
@RequestMapping(value = "")
public class LoginController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
    @Resource
    private PropertyUserService propertyUserService;
    @Resource
    private UserResourceService userResourceService;
    @Resource
    private ShiroRealm shiroRealm;

    @RequestMapping(value = "/doLogin", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Result login(ShUser userParam, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result msg = null;
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken();
        token.setUsername(userParam.getLoginName().trim());
        token.setPassword(SHACipher.encrypt(userParam.getLoginPwd().trim()).toCharArray());
        try {
            subject.login(token);
            subject.isPermitted("/test");
            msg = Result.success("登录成功");
        } catch (UnknownSessionException use) {
            subject = new Subject.Builder().buildSubject();
            try {
                subject.login(token);
                subject.isPermitted("/test");
                msg = Result.success("登录成功");
            } catch (Exception e) {
                msg = Result.failure("登录出错：" + e.getMessage());
            }
        } catch (UnknownAccountException ex) {
            LOGGER.error("登录出错1：", ex);
            msg = Result.failure("登录出错：账户不存在");
        } catch (IncorrectCredentialsException ice) {
            LOGGER.error("登录出错2：", ice);
            msg = Result.failure("登录出错：密码错误");
        } catch (LockedAccountException lae) {
            LOGGER.error("登录出错3：", lae);
            msg = Result.failure("登录出错：账户锁定");
        } catch (AuthenticationException ae) {
            LOGGER.error("登录出错4：", ae);
            msg = Result.failure("登录出错：认证失败");
        } catch (Exception e) {
            LOGGER.error("登录出错5：", e);
            msg = Result.failure("登录出错：" + e.getMessage());
        }
        // add by dhc 登录成功，设置当前区域
        if (msg.isSuccess()) {
            if (UserHolder.isSuperAdmin()) {
                UserHolder.resetResidenceId(1l);
            } else {
                if (null != UserHolder.getResidences() && UserHolder.getResidences().size() > 0)
                    UserHolder.resetResidenceId(UserHolder.getResidences().get(0).getId());
            }
        }
        return msg;
    }

    @RequestMapping("/logout")
    public String logout() {
        // UserHolder.removeCurrentUser();
        // Subject subject = SecurityUtils.getSubject();
        // subject.logout();
        return "/login";
    }

}
